# Maintainer: Ilya Rakhlin <i.rakhlin@gmail.com>

_realname=libressl
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=3.1.1
pkgrel=1
pkgdesc="LibreSSL Encryption (mingw-w64)"
arch=('any')
url='https://www.libressl.org/'
license=('BSD')
options=('staticlibs' 'strip')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc")
source=("https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/${_realname}-${pkgver}.tar.gz"
        "0001-libressl_relocation-msys.patch"
        "0002-libressl_relocation-tests.patch")
sha256sums=('bdc6ce5ebb3a2eafc4c475f7eeaa5f0a8e60d9bead01efb76e2e254242b6db00'
            'cf5ac3ceade7b2b51c6ccbfd6d054dbba4a6fb7375427c5defa3ca90d5b71a47'
            '06500c7f09c2067b17e00d9fa4feb6aec922b8525f710a0dea43bd873a5f447b')

prepare() {
  cd ${srcdir}/${_realname}-${pkgver}
  patch -p1 -i ${srcdir}/0001-libressl_relocation-msys.patch
  patch -p1 -i ${srcdir}/0002-libressl_relocation-tests.patch
  mv libtls.pc.in liblibretls.pc.in
  mv libcrypto.pc.in liblibrecrypto.pc.in
  mv libssl.pc.in liblibressl.pc.in
  mv openssl.pc.in libressl.pc.in
  mv apps/openssl/openssl.c apps/openssl/libressl.c
  autoreconf -fiv
}

build() {
  LDFLAGS+=" -fstack-protector"

  cd "${srcdir}"/${_realname}-${pkgver}
  [[ -d "${srcdir}"/build-${CARCH}-shared ]] && rm -rf "${srcdir}"/build-${CARCH}-shared
  [[ -d "${srcdir}"/build-${CARCH}-static ]] && rm -rf "${srcdir}"/build-${CARCH}-static
  mkdir -p "${srcdir}"/build-${MINGW_CHOST}-shared "${srcdir}"/build-${MINGW_CHOST}-static

  msg "Building static lib..."
  (cd "${srcdir}"/build-${MINGW_CHOST}-static
  ../${_realname}-${pkgver}/configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --target=${MINGW_CHOST} \
    --enable-static \
    --disable-shared \
    --disable-tests \
    --with-openssldir=${MINGW_PREFIX}/share/libressl
  make
  )

  msg "Building shared library..."
  (cd "${srcdir}"/build-${MINGW_CHOST}-shared
  ../${_realname}-${pkgver}/configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --target=${MINGW_CHOST} \
    --enable-shared \
    --disable-static \
    --disable-tests \
    --with-openssldir=${MINGW_PREFIX}/share/libressl
  make
  )
}

check() {
  cd "${srcdir}"/build-${MINGW_CHOST}-static
  make check
}

package() {
  cd "${srcdir}"/build-${MINGW_CHOST}-static
  make DESTDIR="${pkgdir}" install || true

  cd "${srcdir}"/build-${MINGW_CHOST}-shared/crypto
  make DESTDIR="${pkgdir}" install || true

  cd "${srcdir}"/build-${MINGW_CHOST}-shared/ssl
  make DESTDIR="${pkgdir}" install || true

  cd "${srcdir}"/build-${MINGW_CHOST}-shared/tls
  make DESTDIR="${pkgdir}" install || true

  mkdir "${pkgdir}"${MINGW_PREFIX}/include/libressl
  mv "${pkgdir}"${MINGW_PREFIX}/include/openssl "${pkgdir}"${MINGW_PREFIX}/include/libressl
}
